import os

def create_directories(project_root, novel_name):
    # 创建cache文件夹下的上传文件名文件夹
    upload_dir = os.path.join(project_root, "cache", novel_name)
    os.makedirs(upload_dir, exist_ok=True)
    return upload_dir


def check_existing_files(upload_dir, novel_name):
    draft_file = os.path.join(upload_dir, f"剧情摘要.txt")
    plot_file = os.path.join(upload_dir, f"章节大纲.txt")
    chapters_file = os.path.join(upload_dir, f"全文大纲.txt")
    
    file_check_msg = []
    if os.path.exists(draft_file):
        file_check_msg.append(f"剧情摘要文件 {draft_file} 已存在")
    if os.path.exists(plot_file):
        file_check_msg.append(f"章节大纲文件 {plot_file} 已存在")
    if os.path.exists(chapters_file):
        file_check_msg.append(f"全书大纲文件 {chapters_file} 已存在")
    
    return file_check_msg, draft_file, plot_file, chapters_file


def save_chapter_files(save_dir, novel_name, chapter_titles, chapter_contents):
    # 按章节保存拆分后的文档
    split_dir = os.path.join(save_dir, f"拆解路径")
    for i, (title, content) in enumerate(zip(chapter_titles, chapter_contents), 1):
        chapter_file = os.path.join(split_dir, f"拆分的第{i}章内容.txt")
        with open(chapter_file, 'w', encoding='utf-8') as f:
            chapter_name = ' '.join(title)
            f.write(f"{chapter_name}\n\n{content}")
    yield {"progress_msg": f"章节已拆分并保存至 {split_dir}"}
    yield {"progress_msg": "解析出章节数：" + str(len(chapter_titles))}
    return split_dir


def save_draft_file(draft_file, chapter_titles, dw_list):
    with open(draft_file, 'w', encoding='utf-8') as f:
        for title, dw in zip(chapter_titles, dw_list):
            chapter_name = ' '.join(title)
            f.write(f"## {chapter_name}\n")
            f.write(dw.x)
            f.write("\n\n")
    return draft_file


def save_plot_file(plot_file, chapter_titles, cw_list):
    with open(plot_file, 'w', encoding='utf-8') as f:
        for title, cw in zip(chapter_titles, cw_list):
            chapter_name = ' '.join(title)
            f.write(f"## {chapter_name}\n")
            if cw is not None:
                f.write(cw.global_context['chapter'])
            f.write("\n\n")
    return plot_file


def save_chapters_file(chapters_file, outline):
    with open(chapters_file, 'w', encoding='utf-8') as f:
        for title, content in outline.xy_pairs:
            f.write(f"## {title}\n")
            f.write(content)
            f.write("\n\n")
    return chapters_file